<template>
  <div>
    <div class="breach-area">
      <div class="title">
        <div class="point"></div>
        <span v-if="!newsId">新建资讯</span>
        <span v-else>修改资讯</span>
      </div>
      <el-row>
        <el-col>
          <el-input v-model="newsTitle"
                    placeholder="标题"></el-input>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-input v-model="author"
                    placeholder="作者"></el-input>
        </el-col>
      </el-row>
      <div class="rich-text-package">
        <rich-text :my-content.sync="newsContent"></rich-text>
      </div>
    </div>
    <div class="foot">
      <el-button @click="uploadNews"
                 type="primary"
                 plain>确认</el-button>
      <el-button @click="() => {this.$router.go(-1)}"
                 plain>取消</el-button>
    </div>
  </div>
</template>

<style lang="scss">
.rich-text-package {
  padding: 5px 20px;
}
.ql-editor {
  min-height: 500px;
}
</style>

<script>
import '@/style/info.scss'
import '@/style/common.scss'
import richText from '@/components/rich-text'
import { HTTPSUCCESS, HTTPDATAFAIL, HTTPPARAMFAIL, HTTPUNKOWNFAIL } from '@/components/constant'
import { api } from '@/api'
import { validatenull } from '@/utils/validate'

export default {
  data() {
    return {
      newsTitle: null,
      newsContent: null,
      author: null
    }
  },
  props: [
    'newsId'
  ],
  activated() {
    this.reload()
    this.getNews()
  },
  components: { richText },
  methods: {
    reload() {
      this.newsTitle = null
      this.newsContent = null
      this.author = null
    },
    getNews() {
      if (this.newsId) {
        this.$http._get(api.SYS_NEWS_INFO, this.newsId).then(
          res => {
            this.newsTitle = res.data.title
            this.newsContent = res.data.content
            this.author = res.data.author
          }
        )
      }
    },
    uploadNews() {
      if (validatenull(this.newsTitle)) return this.$msg._message('请填入标题', 'warning')
      if (validatenull(this.newsContent)) return this.$msg._message('请填入资讯内容', 'warning')
      const preview = this.newsContent.replace(/\s*/g, '').replace(/<[^>]+>/g, '').replace(/↵/g, '').replace(/[\r\n]/g, '')
      const params = {
        newsId: this.newsId || null,
        title: this.newsTitle,
        author: this.author,
        content: this.newsContent,
        resume: preview.length > 50 ? preview.slice(0, 50) : preview
      }
      this.$http.post(api.SYS_NEWS_UPLOAD, params).then(
        res => {
          if (res.code === HTTPSUCCESS) {
            this.$msg._message('上传成功', 'success')
            this.$router.push({ name: 'news' })
          } else {
            this.$msg._message(res.data.msg, 'error')
          }
        }
      )
    }
  }
}
</script>
